package com.example.dictionary.service;

import com.example.dictionary.config.DictionaryProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 应用启动初始化服务
 */
@Service
public class StartupService implements CommandLineRunner {
    
    private static final Logger log = LoggerFactory.getLogger(StartupService.class);
    
    private final DictionaryProperties properties;
    private final DownloadPathMappingService pathMappingService;
    
    public StartupService(DictionaryProperties properties, DownloadPathMappingService pathMappingService) {
        this.properties = properties;
        this.pathMappingService = pathMappingService;
    }
    
    @Override
    public void run(String... args) throws Exception {
        log.info("词典服务启动初始化开始...");
        
        // 创建必要的目录
        createDirectories();
        
        // 加载下载路径映射（已在 @PostConstruct 中自动加载，这里仅打印信息）
        logDownloadPathMappings();
        
        // 打印配置信息
        printConfiguration();
        
        log.info("词典服务启动初始化完成");
    }
    
    /**
     * 创建必要的目录
     */
    private void createDirectories() {
        try {
            // 创建数据存储目录
            Path dataPath = Paths.get(properties.getStorage().getPath());
            if (!Files.exists(dataPath)) {
                Files.createDirectories(dataPath);
                log.info("创建数据存储目录: {}", dataPath);
            }
            
            // 创建RocksDB目录
            Path rocksdbPath = Paths.get(properties.getStorage().getRocksdbPath());
            if (!Files.exists(rocksdbPath)) {
                Files.createDirectories(rocksdbPath);
                log.info("创建RocksDB目录: {}", rocksdbPath);
            }
            
            // 创建日志目录
            Path logPath = Paths.get("./logs");
            if (!Files.exists(logPath)) {
                Files.createDirectories(logPath);
                log.info("创建日志目录: {}", logPath);
            }
            
            // 创建映射文件目录
            Path dictPath = Paths.get("data/dict");
            if (!Files.exists(dictPath)) {
                Files.createDirectories(dictPath);
                log.info("创建映射文件目录: {}", dictPath);
            }
            
        } catch (Exception e) {
            log.error("创建目录失败", e);
        }
    }
    
    /**
     * 打印下载路径映射信息
     */
    private void logDownloadPathMappings() {
        var mappings = pathMappingService.getAllMappings();
        log.info("=== 下载路径映射 ===");
        if (mappings.isEmpty()) {
            log.info("暂无下载路径映射记录");
        } else {
            log.info("已加载 {} 条下载路径映射:", mappings.size());
            mappings.forEach((key, entry) -> {
                log.info("  {} -> {} (下载时间: {})", 
                        key, 
                        entry.getDownloadPath(), 
                        entry.getDownloadTime());
            });
        }
        log.info("==================");
    }
    
    /**
     * 打印配置信息
     */
    private void printConfiguration() {
        log.info("=== 词典服务配置信息 ===");
        log.info("存储类型: {}", properties.getStorage().getType());
        log.info("存储路径: {}", properties.getStorage().getPath());
        log.info("RocksDB路径: {}", properties.getStorage().getRocksdbPath());
        log.info("最大并发下载数: {}", properties.getDownload().getMaxConcurrent());
        log.info("下载超时时间: {}秒", properties.getDownload().getTimeoutSeconds());
        log.info("解析批次大小: {}", properties.getParsing().getBatchSize());
        log.info("解析线程池大小: {}", properties.getParsing().getThreadPoolSize());
        
        log.info("=== 词典源配置 ===");
        properties.getSources().forEach(source -> {
            log.info("源名称: {}, 启用: {}, 格式: {}, 描述: {}", 
                    source.getName(), 
                    source.isEnabled(), 
                    source.getFormat(), 
                    source.getDescription());
        });
        log.info("========================");
    }
}
